package com.mobiftpcms.webapp.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.mobiftpcms.model.Station;
import com.mobiftpcms.service.StationManager;

@Controller
@RequestMapping("/admin/station")
public class StationController extends BaseFormController {
	private StationManager stationManager;
	
	@Autowired
	public void setStationManager(StationManager stationManager) {
		this.stationManager = stationManager;
	}
	
	public StationManager getStationManager() {
		return stationManager;
	}
	
	public StationController() {
		setCancelView("redirect:/mainMenu");
		setSuccessView("redirect:/mainMenu");
	}
	
	@ModelAttribute
	@RequestMapping(method = RequestMethod.GET)
	public Station showForm() {
		return new Station();
	}
	
	@RequestMapping(method = RequestMethod.POST)
	public String onSubmit(Station station, BindingResult errors, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (request.getParameter("cancel") != null) {
            return getCancelView();
        }

        if (log.isDebugEnabled()) {
            log.debug("entering 'onSubmit' method...");
        }
        
        try {
        	this.getStationManager().saveStation(station);
        } catch(AccessDeniedException ade) {
        	// thrown by UserSecurityAdvice configured in aop:advisor userManagerSecurity
            log.warn(ade.getMessage());
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return null; 
        }
        
        return getSuccessView();
        
	}
}
